'use strict';
const request = require('request');
const co = require('co');
const debug = require('debug')('debug');
/**
 * @param  {String} url      [要爬取的sfda地址]
 * @param  {String} testUrl [此url爬取到的url]
 * @return {}          [description]
 */
const get = function(url, testingUrl, { retry = 30, timeout = 15000 } = {}) {
  url = `${url}`;

  return co(function *() {
    while(--retry !== 0) {
      debug(retry);
      try {
        const ret = yield new Promise((resolve, reject) => {
          request({
            url: encodeURI(url),
            timeout
          }, function(err, res, body) {
            if(err)
              reject(err);
            else
              resolve({res, body});
          });
        });

        debug(ret.body.indexOf(loadFlag) !== -1);
        if(ret.body.indexOf(loadFlag) !== -1) {
          return Promise.resolve({
            load: true,
            res: ret.res,
            body: ret.body
          });
        }
        else {
          cookieHelper.addResCookieToCookies(ret.res, cookies);
        }
      } catch (e) {
        console.error(e);
      }
    }
    return Promise.resolve({
      load: false,
    });
  });
};

module.exports = {
  get
};
